//
//  Fun_AlertViewController.m
//  YinHang
//
//  Created by 张亚哲 on 14/11/28.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "Fun_AlertViewController.h"

@interface Fun_AlertViewController ()<ASIHTTPRequestDelegate>{
    
    __weak IBOutlet UIButton *commit_btn;
    
    __weak IBOutlet UIScrollView *mainView;
    
    IBOutletCollection(UITextField) NSArray *textArr;
    MBProgressHUD *postHud;
    //参数
    ASIFormDataRequest *_request;
    NSString *action;
    NSMutableDictionary *paramsDict;
}

@end

@implementation Fun_AlertViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(id)initWithId:(NSString *)idstr titleArr:(NSArray *)titleArr titleDic:(NSDictionary *)titleDic{
    self = [super init];
    if (self) {
        _titleArr = [titleArr mutableCopy];
        _idstr = idstr;
        _titleDic = [titleDic mutableCopy];
    }
    return self;
}
-(void)viewDidLayoutSubviews{
    UIScreen *screen = [UIScreen mainScreen];
    mainView.frame = CGRectMake(0, 0, screen.bounds.size.width, screen.bounds.size.height - 64);
    mainView.contentSize = CGSizeMake(screen.bounds.size.width, 568 - 64);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"导航栏目修改";
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    commit_btn.backgroundColor = APP_COLOR;
    commit_btn.layer.cornerRadius = 5.0;
    for (int i = 0; i < textArr.count; i++) {
        UITextField *text = textArr[i];
        text.text = _titleDic[_titleArr[i]];
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc{
    _titleDic = nil;
    _idstr = nil;
    _titleArr = nil;
    [_request cancel];
    _request = nil;
}
-(void)back{
    [_delegate refreshAlertData];
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)commit:(id)sender {
    [self postRequest];
}

-(void)postRequest{
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在加载，请稍后...";
        }
        
        _request = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        _request.requestMethod = @"POST";
        // 设置超时时间
        _request.timeOutSeconds = 60;
        _request.delegate = self;
        // 设置参数
        action = @"DaohangLanmuupdate";
        
        paramsDict = [NSMutableDictionary dictionary];
        //uid会员名
        [paramsDict setValue:UNAME forKey:@"uid"];
        [paramsDict setValue:_idstr forKey:@"id"];
        for (int i = 1; i <= 10 ; i++) {
            NSString *title = [NSString stringWithFormat:@"Title%i",i];
            UITextField *text = textArr[i - 1];
            [paramsDict setObject:text.text forKey:title];
        }
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        _request.postBody = [paramsData mutableCopy];
        
        [_request startAsynchronous];
    }
}

#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    postHud.hidden = YES;
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        
        if (errorCode == 0) {
            postHud.hidden = YES;
            [SVProgressHUD showSuccessWithStatus:@"修改成功"];
        }
        
    } else {
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    for (UITextField *text in textArr) {
        [text resignFirstResponder];
    }
}

@end
